/*
 *Copyright (C), 2017, Makerfire. Co., Ltd.
 *Author: redScarf
 *Version: 1.0
 *Date: 2018-8-01
 *Function: spi interface
 */
#include "SPI.h"
#include "stm8s_spi.h"

/*
	CSN:PA3
	SCK:PC5
	MOSI:PC6
	MISO:PC7
*/

#define SCK_GPIO GPIOC
#define SCK_PIN GPIO_PIN_5

#define MOSI_GPIO GPIOC
#define MOSI_PIN GPIO_PIN_6

#define MISO_GPIO GPIOC
#define MISO_PIN GPIO_PIN_7

#define CSN_GPIO GPIOA
#define CSN_PIN GPIO_PIN_3

#define CSN_H GPIO_WriteHigh(CSN_GPIO, CSN_PIN)
#define CSN_L GPIO_WriteLow(CSN_GPIO, CSN_PIN)

void spiInit(void)
{
    CLK_PeripheralClockConfig(CLK_PERIPHERAL_SPI,ENABLE);
    
	//输出引脚配置
    GPIO_Init(CSN_GPIO, CSN_PIN, GPIO_MODE_OUT_PP_LOW_FAST);
    GPIO_Init(SCK_GPIO, SCK_PIN, GPIO_MODE_OUT_PP_LOW_FAST);
    GPIO_Init(MOSI_GPIO, MOSI_PIN, GPIO_MODE_OUT_PP_LOW_FAST);
    //输入引脚配置
    GPIO_Init(MISO_GPIO, MISO_PIN, GPIO_MODE_IN_PU_NO_IT);

    /* Initialize SPI mode master 0 */
	SPI_Init( SPI_FIRSTBIT_MSB,
			SPI_BAUDRATEPRESCALER_4,
			SPI_MODE_MASTER,
			SPI_CLOCKPOLARITY_LOW,
			SPI_CLOCKPHASE_1EDGE,
			SPI_DATADIRECTION_2LINES_FULLDUPLEX,
			SPI_NSS_SOFT, 
            0x07);

	/* SD_SPI enable */
	SPI_Cmd( ENABLE);

	CSN_H;
}

uint8_t spi_master_transmit_receive(
		uint8_t* send_data,
		uint8_t* receive_data,
		uint16_t length)
{

	uint16_t time_out= 5000;

	/*!< Wait until the transmit buffer is empty */
	while((!SPI_GetFlagStatus(SPI_FLAG_TXE))&& (--time_out));
	if(!time_out) return 1;

	/* Empty receive buffer */
	if(SPI_GetFlagStatus(SPI_FLAG_RXNE))
	{
		uint8_t temp_data=SPI_ReceiveData();
	}

	/* Enable communication */
	CSN_L;

	for(uint16_t i=0; i< length; i++)
	{
		SPI_SendData(*(send_data+i));

		if(receive_data != NULL)
		{
			while((!SPI_GetFlagStatus(SPI_FLAG_RXNE))&& (--time_out));
			if(!time_out) return 1;
			*(receive_data+i)=SPI_ReceiveData();
		}
		else
		{
			while((!SPI_GetFlagStatus(SPI_FLAG_TXE))&& (--time_out));
			if(!time_out) return 1;
		}
	}

	/* Disable communication */
	CSN_H;
	return 0;
}
